#ifndef _SEC_MANAGER_H_
#define _SEC_MANAGER_H_

#include <vector>
#include <algorithm>

// 用于查找值在哪个区间内,并返回区间对应的数据
// 如 [1~100 : A] [101~340 : B] [341~7777 : C] [7778~10000 : D]
// 给定数值 220, 查询结果返回B
template<class T>
class CSecManager
{
public:
    struct sd
    {
        sd(long long _v, T &_td) : _val(_v), _d(_td){}
        long long _val;
        T _d;
    };

    CSecManager(){}
    ~CSecManager(){}
    void Add(long long val, T d);
    bool Find(long long val, T &d);
    void Clear() { m_data.clear(); }
    const std::vector<sd>& Data() { return m_data; }

private:
    bool _Find(long long val, T &d, int from, int to);

private:
    struct less
    {
        bool operator()(const sd &sd1, const sd &sd2)
        {
            return sd1._val < sd2._val;
        }
    };
    std::vector<sd> m_data;
};

template<class T>
void CSecManager<T>::Add(long long val, T d)
{
    sd sd1(val, d);
    m_data.insert( std::upper_bound(m_data.begin(), m_data.end(), sd1, less()), sd1 );
}

template<class T>
bool CSecManager<T>::Find(long long val, T &d)
{
    return _Find( val, d, 0, m_data.size()-1 );
}

template<class T>
bool CSecManager<T>::_Find(long long val, T &d, int from, int to)
{
    if( to == from )
    {
        if( m_data[to]._val < val ) 
            return false;
        d = m_data[to]._d;
        return true;
    }
    int mid = (from + to) / 2;
    if( val <= m_data[mid]._val )
        return _Find( val, d, from, mid );
    else
        return _Find( val, d, mid+1, to );
}

#endif


